package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.springframework.beans.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /*
    * 用户登录
    * */
    @Override
    public ResponseResult<AdUser> loginAdmin(AdUserDTO adUserDTO) {
        //1.参数校验,判断参数为不为空
        if (adUserDTO == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"参数为空");
        }
        //2.校验用户名和密码是否为空
        String name = adUserDTO.getName();
        String password = adUserDTO.getPassword();
        if (StringUtils.isBlank(name) || StringUtils.isBlank(password)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        //3.判断用户名在数据库中是否存在
        //用封装好的查村方法，getOne返回结果为实体类且只有一个，count返回的是查到了几个
        AdUser one = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if (one == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"该用户名不存在");
        }
        //4.判断密码是否正确，密码是加密的
        String pwd=password+one.getSalt();
        password= DigestUtils.md5DigestAsHex(pwd.getBytes());
        if (!password.equals(one.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
       //5.判断用户状态是否有效
        if(9!=one.getStatus().intValue()){
            System.out.println(one.getStatus().intValue());
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态无效");
        }
        //数据库中也要修改登录时间
        one.setLoginTime(new Date());
        updateById(one);
        String token = AppJwtUtil.getToken(one.getId().longValue());
       //将返回的token和数据封装到map集合中
        AdUserVo userVo = new AdUserVo();
        BeanUtils.copyProperties(one,userVo);
        Map map = new HashMap<>();
        map.put("token",token);
        map.put("user",userVo);
        return ResponseResult.okResult(map);
    }
}
